//
//  WBImageView.m
//  WXWeiBo
//
//  Created by 朱思明 on 15/9/22.
//  Copyright (c) 2015年 朱思明. All rights reserved.
//

#import "WBImageView.h"

@implementation WBImageView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor blackColor];
        self.contentMode = UIViewContentModeScaleAspectFit;
        
        // 点击事件
        // 01 开启触摸
        self.userInteractionEnabled = YES;
        // 02 创建一个手势对象
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomInView)];
        [self addGestureRecognizer:tap];
    }
    return self;
}

#pragma mark - 点击图片放大事件
- (void)zoomInView
{
    // 1.创建scrollView
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        // 添加手势
        // 01 长按保存图片
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
        [_scrollView addGestureRecognizer:longPress];
        
        // 02 关闭放大视图
        UITapGestureRecognizer *tap= [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomOutView)];
        [_scrollView addGestureRecognizer:tap];
    }
    // 初始化滑动视图,并添加到window
    // 01 设置滑动视图完全透明
    _scrollView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.0];
    // 02 把滑动视图添加到window上
    [self.window addSubview:_scrollView];
    
    // 2.创建放大的图片视图
    if (_originalImageView == nil) {
        _originalImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        _originalImageView.contentMode = UIViewContentModeScaleAspectFit;
    }
    // 初始化图片视图并添加到滑动视图上
    // 01 设置视图的大小和位置
    _originalImageView.frame = [self convertRect:self.bounds toView:self.window];
    // 02 设置放大视图的默认图片
    _originalImageView.image = self.image;
    [_scrollView addSubview:_originalImageView];
    
    // 3.图片放大滑动视图变黑
    [UIView animateWithDuration:.35 animations:^{
        _scrollView.backgroundColor = [UIColor blackColor];
        // image.height / image.width  = height / kScreenWidth
        float height = _originalImageView.image.size.height /_originalImageView.image.size.width * kScreenWidth;
        // 设置滑动视图的内容大小
        if (height > _scrollView.height) {
            _originalImageView.frame = CGRectMake(0, 0, kScreenWidth, height);
            _scrollView.contentSize = CGSizeMake(kScreenWidth, height);
        } else {
            _originalImageView.frame = _scrollView.bounds;
            _scrollView.contentSize = _scrollView.frame.size;
        }
    } completion:^(BOOL finished) {
        // 下载大图显示
        if (_originalImageUrl != nil) {
            [_originalImageView sd_setImageWithURL:[NSURL URLWithString:_originalImageUrl] placeholderImage:_originalImageView.image options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                // 显示下载进度
                if (_progressView == nil) {
                    _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 200, kScreenWidth, 30)];
                }
                [_scrollView addSubview:_progressView];
                _progressView.progress = (float)receivedSize / expectedSize;
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                _originalImageView.image = image;
                // 移除进度视图
                [_progressView removeFromSuperview];
            }];
        }
    }];
    
}

// 退出放大视图
- (void)zoomOutView
{
    // 01 如果进度条还在
    if (_progressView.superview != nil) {
        // 从父视图上移除
        [_progressView removeFromSuperview];
    }
    
    // 02 开始执行缩小动画
    [UIView animateWithDuration:.35 animations:^{
        // 滑动视图变透明
        _scrollView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
        // 放大图片缩小
        _originalImageView.frame = [self convertRect:self.bounds toView:self.window];
    } completion:^(BOOL finished) {
        // 移除图片和滑动视图
        [_scrollView removeFromSuperview];
        [_originalImageView removeFromSuperview];
    }];
}

#pragma mark - 视图长按手势
- (void)longPressAction:(UILongPressGestureRecognizer *)longPress
{
    if (longPress.state == UIGestureRecognizerStateBegan) {
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"保存到相册" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"保存到相册", nil];
        [sheet showInView:_scrollView];
    }
    
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
//        UIImageWriteToSavedPhotosAlbum(_originalImageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        UIImageWriteToSavedPhotosAlbum(_originalImageView.image, self, nil, nil);

 [self alertActionWithTitle:@"保存成功" action:^() {
//        UIImageWriteToSavedPhotosAlbum(_originalImageView.image, nil, nil, nil);
     
    }];

    }
}
// 提示框
- (void)alertActionWithTitle:(NSString *)title action:(void(^)())action
{
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    
    /**
     * 弹出提示框并保存图片
     */
    [self.ViewController presentViewController:alertC animated:YES completion:^{
        
        if (action) {
            action();
        }
        
    }];
    
    /**
     * 添加延迟线程让视图消失
     */
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [alertC dismissViewControllerAnimated:YES completion:nil];
        
    });
}


// 图片保存完成
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSLog(@"保存完成");
}

@end
